// shoppingcart.js
/**
 * 微信端购物车不维护选中状态（不与服务器同步商品选中与否）
 */
var cart = require('../../utils/cart.js');
var util = require('../../utils/util.js');
var cartapi = require('../../component/service/cartapi.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hidden:false,
    items: [],
    sellers:[],
    selectAll:false,
    totalAmount:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '采购清单'
    })
  },
  //切换回购物车时，重新获取数据
  onShow:function(){
    //使用新方法，非登录用户不得使用购物车
    this.getData();
  },

  /** 
   * 使用新方法，非登录用户不得使用购物车 -- update by yzl 20171228
   * 获取用户购物车商品信息，提交支付时，只提交sku_id以及quantity，价格根据服务器价格计算 
   * 若用户未登录，则获取本地商品信息，若用户已登录，则获取服务器信息
  */
  getData: function(){
    var that = this;
    //用户未登录,跳转至登录页面
    if (getApp().globalData.platUser == null) {
      wx.navigateTo({
        url: '../login/login?returnType=true'
      });
      /**
      var res = wx.getStorageInfoSync();
      var skus = [];
      for (var i = 0; i < res.keys.length; i++) {
        try {
          var sku = wx.getStorageSync(res.keys[i]);
          if (typeof (sku) != 'undefined' && typeof (sku.skuId) != 'undefined')
            skus.push(sku);
        } catch (e) { }
      }
      that.setData({
        items: skus,
        hidden:true
      })
      that.calTotal();
      */
    } else {//用户为登录状态
      let that = this;
      cartapi.groups(function(res){
        that.setData({
          items:res
        })
        that.calTotal();
      })
    }
  },
  //选中/取消选中卖家
  selectSeller:function(event){
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    let selectStatus = true;
    if (this.data.items[idx].isChecked){
      selectStatus = false;
    }  
    cartapi.clickSeller(selectStatus,that.data.items[idx].seller,function(res){
      that.data.items[idx] = res[0];
      that.data.items[idx].isChecked = selectStatus;
      for(let i = 0;i < that.data.items[idx].items.length;i++){
         that.data.items[idx].items[i].isChecked = selectStatus;
      }
      that.setData({
         items: that.data.items
      });
      that.calTotal();
    })
  },
  //选中/取消选中 商品
  selectItem:function(event){
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    let index = event.currentTarget.dataset.index;
    let sku = this.data.items[idx].items[index];
    let selectStatus = true;
    if (sku.isChecked){
      selectStatus = false;
    }
    cartapi.clickSingle(selectStatus,sku.sysNo,function(res){
      that.data.items[idx] = res[0];
      that.setData({
        items: that.data.items
      });
      that.calTotal();
    });    
  },
  //选中/取消选中 所有商品
  selectAll:function(){
    if(typeof(this.data.items)=='undefined')
      return;
    let that = this;
    let selectAll = !this.data.selectAll;
    cartapi.clickAll(selectAll,function(res){
      for(let i = 0;i<res.length;i++){
        res[i].isChecked = selectAll;
      }
      that.setData({
        items: res,
        selectAll:selectAll
      });
      that.calTotal();
    })
  },
  //商品数量变更时，校验变更是否合法
  verifyQty:function(sku,qty,callback){
    sku.quantity = sku.quantity + qty;
    if (sku.quantity > sku.actualWholesaleMaxQuantity) sku.quantity = sku.actualWholesaleMaxQuantity;

  },
  //增加商品数量
  add:function(event){
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    let index = event.currentTarget.dataset.index;
    let sku = this.data.items[idx].items[index];
    sku.quantity = sku.quantity + 1;
    if (sku.quantity > sku.actualWholesaleMaxQuantity){
      sku.quantity = sku.actualWholesaleMaxQuantity;
      return;
    }
    let sellerChecked = this.data.items[idx].isChecked;
    cartapi.setQty(sku.sysNo,sku.quantity,function(res){
      res[0].isChecked = sellerChecked;
      that.data.items[idx] = res[0];
      that.setData({
         items: that.data.items
      });
      that.calTotal();
    });
    //this.effectPrice(this.data.items[index].skuId,index);
  },
  //减少商品数量
  reduce:function(event){
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    let index = event.currentTarget.dataset.index;
    let sku = this.data.items[idx].items[index];
    if(sku.quantity<(sku.wholesaleMinQuantity+1)) return;
    sku.quantity = sku.quantity - 1;
    let sellerChecked = this.data.items[idx].isChecked;
    cartapi.setQty(sku.sysNo,sku.quantity,function(res){
      res[0].isChecked = sellerChecked;
      that.data.items[idx] = res[0];
      that.setData({
         items: that.data.items
      });
      that.calTotal();
    });
    // this.effectPrice(this.data.items[index].skuId,index);
  },
  //手动修改数量
  quantityChange:function(e){
    let that = this;
    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let sku = this.data.items[idx].items[index];
    var reg = /^[1-9]+[0-9]*]*$/; //判断正整数
    var changetQty = e.detail.value;
    if(reg.test(changetQty)){
      changetQty = parseInt(changetQty);
      if(changetQty<sku.wholesaleMinQuantity) changetQty=sku.wholesaleMinQuantity;
      if(changetQty>sku.actualWholesaleMaxQuantity) changetQty=sku.actualWholesaleMaxQuantity;
      sku.quantity = changetQty;
      let sellerChecked = this.data.items[idx].isChecked;
      cartapi.setQty(sku.sysNo,sku.quantity,function(res){
        res[0].isChecked = sellerChecked;
        that.data.items[idx] = res[0];
        that.setData({
           items: that.data.items
        });
        that.calTotal();
      });
      // this.effectPrice(this.data.items[index].skuId,index);
    }
  },
  //设置有效价格 后台列表按minQuantity升序，所以最后一个符合要求的价格为生效价格
  //若为品鉴装，则不去查询价格
  //过期，后台直接返回可用价格 20171228
  effectPrice:function(skuId,index){
    //若为品鉴装，则不去查询价格
    if(this.data.items[index].isSample) return;
    var that = this;
    if(typeof(this.data.items[index].skuPrices) == 'undefined'||this.data.items[index].skuPrices.length<=0){
      wx.request({
        url: getApp().globalData.host + 'webapp/resource/skuPrices.html?skuId=' + skuId,
        header: getApp().globalData.header,
        success: function (res) {
          if(res.data.length>0&&typeof(res.data[0].priceId)!='undefined'){
            that.data.items[index].skuPrices = res.data;
            that.setData({
              items: that.data.items
            });    
            that.computePrice(index);
          }
        }
      })
    }else
      that.computePrice(index);
  },
  computePrice:function(itemIndex){
    if(typeof(this.data.items[itemIndex].skuPrices) == 'undefined'||this.data.items[itemIndex].skuPrices.length<=0)
      return;
    var index = null;
    for(var i = 0;i<this.data.items[itemIndex].skuPrices.length;i++){
      if(this.data.items[itemIndex].quantity>=this.data.items[itemIndex].skuPrices[i].minQuantity)
        index = i;
    }
    if(null!=index){
      this.data.items[itemIndex].price = this.data.items[itemIndex].skuPrices[index].price;
    }
    this.setData({
      items: this.data.items
    });
    this.calTotal();
  },
  //好像没用
  addShoppingCart: function(e){
    cart.add(this.data.sku,this.data.quantity,true);
  },
  //移除购物车商品
  removeItem:function(event){
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    let index = event.currentTarget.dataset.index;
    let sku = this.data.items[idx].items[index];
    wx.showModal({
      title: '提示',
      content: '确认要移除该商品吗？',
      success: function(res) {
        if (res.confirm) {
          cartapi.deleteSingle(sku.sysNo,function(res){
            cartapi.groups(function(res){
              that.setData({
                items:res
              })
              that.calTotal();
            })
          });          
        }
      }
    })
  },
  //
  calTotal:function(){
    var totalAmount = 0;
    for(var i=0;i<this.data.items.length;i++){
      for(let j = 0;j<this.data.items[i].items.length;j++){
        //if(obj%1 === 0)
        this.data.items[i].items[j].totalPrice = this.data.items[i].items[j].price*this.data.items[i].items[j].quantity;
        if (this.data.items[i].items[j].isChecked){
          totalAmount += (this.data.items[i].items[j].price*this.data.items[i].items[j].quantity);
        }
      }      
    }
    this.setData({
       totalAmount: totalAmount,
       items:this.data.items,
       hidden:true
    });
  },
  //结算-生成订单
  doOrder:function(){
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      wx.navigateTo({
        url: '../login/login?channel=shopping'
      });
    }else{
      wx.request({
        url: getApp().globalData.host + 'webapp/orders/confirmCart.html',
        header: getApp().globalData.header,
        success: function (res) {
          if (typeof (res.data) != 'undefined' && typeof (res.data.orderId) != 'undefined')
            wx.navigateTo({
              url: '../confirm/confirm?orderId=' + res.data.orderId
            });
          else{
            wx.showModal({
              title: '预定失败',
              content:res.data,
              showCancel:false
            })
          }
        },
        fail: function (res) { },
        complete: function (res) { }
     })
    }
  }

})